﻿using System;
using System.Collections.Generic;
using System.Linq;
using ReagentStore.DAL;
using ReagentStore.ERM;
using ReagentStore.Resources.Properties;
using ReagentStore.UTL;

namespace ReagentStore.BLL
{
	public class ReagentBLL
	{
		public readonly ReagentDAL DALAccessor = new ReagentDAL();

		private void CheckParams(Reagent reagent)
		{
			reagent.Name = reagent.Name.Regular();
			reagent.Unit = reagent.Unit.Regular();

			if (string.IsNullOrEmpty(reagent.Name) || string.IsNullOrEmpty(reagent.Unit))
				throw new ApplicationException(DefaultResources.REAGENT_INVALID_PARAM);

			if ((reagent.StandingCount < 0) || (reagent.AlertCount < 0))
				throw new ApplicationException(DefaultResources.REAGENT_INVALID_PARAM);

			if (reagent.StandingCount <= reagent.AlertCount)
				throw new ApplicationException(DefaultResources.REAGENT_INVALID_PARAM);

			if (reagent.AlertPeriod < 1)
				throw new ApplicationException(DefaultResources.REAGENT_INVALID_PARAM);

			Reagent exist =
				DALAccessor.GetEntities().SingleOrDefault(
					s => reagent.Name.Equals(s.Name, StringComparison.CurrentCultureIgnoreCase));
			if (exist != null)
				if (reagent.CatalogID.Equals(exist.CatalogID))
					throw new ApplicationException(DefaultResources.REAGENT_EXIST);

			Catalog catalog = new CatalogDAL().GetEntityById(reagent.CatalogID);
			if (catalog == null)
				throw new ApplicationException(DefaultResources.CATALOG_NOT_FOUND);
		}

		private void CheckEntityUpdatable(Reagent reagent)
		{
			Reagent updation = DALAccessor.GetEntityById(reagent.ReagentID);
			if (updation == null)
				throw new ApplicationException(DefaultResources.REAGENT_NOT_FOUND);
		}

		public void Insert(Reagent reagent)
		{
			CheckParams(reagent);
			reagent.ReagentID = 0;
			DALAccessor.Insert(reagent);
		}

		public void Update(Reagent reagent)
		{
			CheckParams(reagent);
			CheckEntityUpdatable(reagent);
			DALAccessor.Update(reagent);
		}

		public void Delete(Reagent reagent)
		{
			CheckEntityUpdatable(reagent);
			DALAccessor.Delete(reagent);
		}

		public int GetQuantity(Reagent reagent)
		{
			var recordDAL = new RecordDAL();

			return recordDAL.GetEntitiesByReagentId(reagent.ReagentID).Sum(record => record.Quantity());
		}

		public IList<Reagent> GetPurchaseList()
		{
			return
				DALAccessor.GetEntities().Where(reagent => GetQuantity(reagent) <= reagent.StandingCount).ToList();
		}

		public IList<Reagent> GetAlertList()
		{
			return DALAccessor.GetEntities().Where(reagent => GetQuantity(reagent) <= reagent.AlertCount).ToList();
		}
	}
}